import axios from 'axios'
import type{
  Captcha,
  Login,
  UserInfoResponse,
  ExaminationResponse,
  ExamDetailResponse,
  MenuResponse,
  searchQuestionParams,
  searchQuestionResponse,
  QuestionTypeItem,
  QuestionListItem,
  sortItem,
  UserListData,
  UserListResponse,
  UpdateUserParams,
  CreateUserParams,
  RoleListResponse,
  ClassListItem,
  removeClassLists
} from './type'

axios.defaults.baseURL = '/api'


// 创建试题
export const createQuestionApi = () => {
  return axios.get('/question/create')
}
// 查询题库-----试题接口
export const QuestionDataApi = (params: searchQuestionParams) => {
  return axios.get<searchQuestionResponse<QuestionListItem[]>>(`/question/list`, {params})
}
// 分类（多选单选）接口
export const QuestionSortApi = () => {
  return axios.get<searchQuestionResponse<sortItem[]>>(`/question/type/list`, {})
}
// 物理化学接口
export const QuestionTypeApi = (params: searchQuestionParams) => {
  return axios.get<searchQuestionResponse<QuestionTypeItem[]>>(`/classify/list`, {params})
}
// 编辑题目
export const editQuestionApi = (id: string) => {
  return axios.post('/question/update?', {id})
}
// 删除题目
export const delQuestionApi = (id: string) => {
  return axios.post(`/question/remove?`,{id})
}
// // 查询试题类型
// export const searchQuestionTypeApi = () => {
//   return axios.get('/question/type/list')
// }
// 创建试题类型
export const createQuestionTypeApi = () => {
  return axios.get('/question/create')
}
// 批量创建试题
export const batchQuestionApi = () => {
  return axios.get('/question//create/multiple')
}

//登录拦截器
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    // console.log('Making request to:', config.url);
    // console.log('Request config:', config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  (response) => {
      return response;
  },
  (error) => {
      if (error.response && error.response.status === 401) {
          // 处理未授权的情况，重定向到登录页面
          localStorage.removeItem('token');
          window.location.href = '/login';
      }
      return Promise.reject(error);
  }
);

// 验证码
export const getCapcha = () => {
  return axios.get<Captcha>("/login/captcha");
};

// 登录
export const login = (data: { username: string; password: string; code: string }) => {
  return axios.post<Login>("/login", data);
};

// 用户信息
export const getUserInfoApi = () => {
  return axios.get<UserInfoResponse>("/user/info");
};
//用户管理
export const getUserListApi = () => {
  return axios.get<UserListData>('/user/list')
}
// 更新用户状态
export const updateUserStatusApi = (userId: string, status: number) => {
  return axios.post('/user/update/status', { userId, status });
}
// // 创建用户
// export const createUserApi = (userData: { username: string; password: string; status: number }) => {
//   return axios.post('/user/create', userData);
// }
// 删除用户
export const deleteUserApi = (userId: string) => {
  console.log('删除用户 API 调用，参数:', { id: userId });
  return axios.post('/user/remove', { id: userId })
    .then(response => {
      console.log('删除用户 API 响应:', response);
      return response;
    })
    .catch(error => {
      console.error('删除用户 API 错误:', error);
      throw error;
    });
}
// 退出登录
export const logoutApi = () => {
  return axios.post("/user/logout");
};
// 用户左侧菜单
export const getUserMenuApi = () => {
  return axios.get<MenuResponse>("/user/menulist");
}
// *班级管理
export const getClassList = (params:{page: number, pagesize: number}) =>{
  return axios.get<ClassListItem>('/studentGroup/list',{
    params
  })
}
// *班级管理删除接口
export const removeClassList =(id:string)=>{
  return axios.post<removeClassLists>('studentGroup/remove', {id})
}

// *班级管理编辑接口
export const updateClassList =(id: string,         // 班级ID，必填
  name: string,       // 班级名称，选填
  classify: string,   // 分类ID，选填
  teacher: string,    // 班主任ID，选填
  description: string, // 班级描述，选填
  status: number )=>{            // 状态，选填)=>{
  return axios.post<removeClassLists>('studentGroup/update', {id,name,classify,teacher,description,status})
}
// *班级管理创建接口
export const createClassList=(teacher:string, name: string, classify: string)=>{
  return axios.post<removeClassLists>('studentGroup/create', { 
    name,
    classify,
    teacher,
  })
}
// // *班级进度接口
// // classify/list
// export const classiftList=(teacher:string, name: string, classify: string, students : number[])=>{
//   return axios.get<removeClassLists>('classify/list')
// }

// 考试记录
export const getExaminationApi = (params?: { pageNum?: number; pageSizeNum?: number }) => {
  return axios.get<ExaminationResponse>("/examination/list", { params });
};

// 考试详情
export const getExamDetailApi = (examId: string) => {
  return axios.get<ExamDetailResponse>(`/examination/detail?id=${examId}`)
}

//用户列表
export const getUserList = (params:{page:number,pagesize:number}) => {
  return axios.get<UserListResponse>('/user/list',{params})
}
//编辑用户
export const editUserApi = (params: UpdateUserParams) => {
  return axios.post<{code:number,msg:string}>('/user/update', params) 
}

//创建用户
export const createUserApi = (params: CreateUserParams) => {
  return axios.post<{code:number,msg:string}>('/user/create', params)  
}

//删除用户
export const delUserApi = (id: string) => {
  return axios.post<{code:number,msg:string}>('/user/remove', {id})
}

//获取角色列表
export const getRoleListApi = () => {
  return axios.get<RoleListResponse>('/role/list')
}